"use client";

import { AtomActionPanel } from "@/components/AtomActionPanel";
import { CreateRoomModal } from "@/components/CreateRoomModal";
import { ImageAtomCard } from "@/components/ImageAtomCard";
import { MidiAtomRow } from "@/components/MidiAtomRow";
import { PlayBar } from "@/components/PlayBar";
import { RadioPlayBar } from "@/components/RadioPlayBar";
import { RoomListItem } from "@/components/RoomListItem";
import { RoomSettingsModal } from "@/components/RoomSettingsModal";
import { SongAtomRow } from "@/components/SongAtomRow";
import { PlaybackProvider, usePlayback } from "@/contexts/PlaybackContext";
import { api } from "@/convex/_generated/api";
import { Id } from "@/convex/_generated/dataModel";
import { useAuthActions } from "@convex-dev/auth/react";
import { useMutation, usePaginatedQuery, useQuery } from "convex/react";
import { CornerUpRight, Loader2, Mic, Plus, Settings, Upload, X } from "lucide-react";
import Link from "next/link";
import { useParams, useRouter, useSearchParams } from "next/navigation";
import { useEffect, useRef, useState, Suspense } from "react";

// Helper component for image thumbnails in attachment dock
function ImageThumbnail({ storageId }: { storageId: string }) {
  const imageUrl = useQuery(
    api.atoms.getImageUrl,
    storageId ? { storageId } : "skip"
  );

  if (!imageUrl) return null;

  return (
    <img
      src={imageUrl}
      alt=""
      className="w-8 h-8 rounded object-cover flex-shrink-0"
    />
  );
}

// Separate component for message rendering to properly use hooks
function MessageItem({
  message,
  user,
  members,
  handleReaction,
  allMessages,
  onAttachAtom,
  onResendMessage,
  onReferenceAtom,
  isInputEmpty,
  isReply = false,
}: {
  message: any;
  user: any;
  members: any;
  handleReaction: (messageId: Id<"messages">, emoji: string, hasReacted: boolean) => void;
  allMessages: any[];
  onAttachAtom?: (atomId: Id<"atoms">) => void;
  onResendMessage?: (content: string, atomIds?: Id<"atoms">[]) => void;
  onReferenceAtom?: (atomId: Id<"atoms">) => void;
  isInputEmpty?: boolean;
  isReply?: boolean;
}) {
  const userReactions = message.reactions?.filter(
    (r: any) => r.userId === user.user?._id
  );

  const isCurrentUser = message.userId === user.user?._id;
  const isAssistant = message.isAssistantMessage;
  const messageAuthor = members?.find(
    (m: any) => m.userId === message.userId
  );
  const authorName = isAssistant
    ? "Orphy"
    : isCurrentUser
    ? "You"
    : messageAuthor?.profile?.displayName ||
      messageAuthor?.user?.name ||
      "User";
  const authorAvatar = messageAuthor?.profile?.avatar;

  // Fetch atoms if message has references
  const atoms = useQuery(
    api.atoms.getByIds,
    message.atomReferences && message.atomReferences.length > 0
      ? { ids: message.atomReferences }
      : "skip"
  );

  // Find reply messages (only for top-level messages)
  const replies = !isReply
    ? allMessages.filter((m) => m.replyToId === message._id)
    : [];

  return (
    <div>
      <div
        key={message._id}
        className={`flex gap-3 -mx-2 px-4 py-3 rounded-lg backdrop-blur-md bg-white/60 dark:bg-gray-900/60 border border-white/20 dark:border-gray-700/30 shadow-lg hover:bg-white/70 dark:hover:bg-gray-900/70 transition-all ${
          isAssistant ? "bg-blue-50/40 dark:bg-blue-900/30" : ""
        } ${isReply ? "ml-8 mt-1 border-l-2 border-blue-200 dark:border-blue-800 pl-3" : ""}`}
      >
      {/* Avatar */}
      <div className="flex-shrink-0">
        {isAssistant ? (
          <div className={`${isReply ? "w-6 h-6" : "w-8 h-8"} rounded-full bg-blue-500 flex items-center justify-center`}>
            <span className={`${isReply ? "text-xs" : "text-sm"} text-white`}>🎵</span>
          </div>
        ) : authorAvatar ? (
          <img
            src={authorAvatar}
            alt={authorName}
            className={`${isReply ? "w-6 h-6" : "w-8 h-8"} rounded-full object-cover`}
          />
        ) : (
          <div className={`${isReply ? "w-6 h-6" : "w-8 h-8"} rounded-full bg-gray-300 dark:bg-gray-600 flex items-center justify-center`}>
            <span className={`${isReply ? "text-xs" : "text-sm"} text-gray-600 dark:text-gray-300`}>
              {authorName.charAt(0).toUpperCase()}
            </span>
          </div>
        )}
      </div>

      <div className="flex-1 overflow-x-auto">
        <div className="flex items-baseline gap-2 mb-1">
          <span className={`font-semibold text-sm ${isAssistant ? "text-blue-600 dark:text-blue-400" : ""}`}>
            {authorName}
            {isAssistant && (
              <span className="ml-1 text-xs bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300 px-1.5 py-0.5 rounded">
                Assistant
              </span>
            )}
          </span>
          <span className="text-xs text-gray-500">
            {new Date(message.timestamp).toLocaleString()}
          </span>
          {onResendMessage && (message.mentions?.includes("suno") || message.mentions?.includes("orphy")) && (
            <button
              onClick={() => onResendMessage(message.content, message.atomReferences)}
              className="ml-auto text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
              title="Resend message"
            >
              <CornerUpRight className="w-3.5 h-3.5" />
            </button>
          )}
        </div>
        <p className="text-sm text-gray-900 dark:text-gray-100">
          {message.content}
        </p>

        {/* LOADING STATE 1: Show assistant thinking indicator */}
        {message.assistantStatus === "processing" && (
          <div className="mt-2 flex items-center gap-2 text-sm text-gray-500">
            <Loader2 className="w-4 h-4 animate-spin" />
            <span>Orphy is thinking...</span>
          </div>
        )}

        {/* Render attached atoms */}
        {atoms && atoms.length > 0 && (
          <div className="mt-3 space-y-3">
            {/* Render song atoms */}
            {atoms.filter((atom) => atom?.type === "song").length > 0 && (
              <div className="space-y-2">
                {atoms.map((atom) => atom && atom.type === "song" && (
                  <SongAtomRow
                    key={atom._id}
                    atom={atom}
                    currentUserId={user.user?._id}
                    onAttachToMessage={isInputEmpty ? undefined : onAttachAtom}
                    onReferenceAtom={isInputEmpty ? onReferenceAtom : undefined}
                  />
                ))}
              </div>
            )}

            {/* Render image atoms in a grid */}
            {atoms.filter((atom) => atom?.type === "image").length > 0 && (
              <div className="grid grid-cols-2 gap-3">
                {atoms.map((atom) => atom && atom.type === "image" && (
                  <ImageAtomCard key={atom._id} atom={atom} currentUserId={user.user?._id} onAttachToMessage={onAttachAtom} />
                ))}
              </div>
            )}

            {/* Render MIDI atoms */}
            {atoms.filter((atom) => atom?.type === "midi").length > 0 && (
              <div className="space-y-2 max-w-full overflow-hidden">
                {atoms.map((atom) => atom && atom.type === "midi" && (
                  <MidiAtomRow key={atom._id} atom={atom} currentUserId={user.user?._id} />
                ))}
              </div>
            )}
          </div>
        )}

        {/* Reactions */}
        {!isAssistant && (
          <div className="flex gap-1 mt-1">
            {["👍", "❤️", "😂", "🎵"].map((emoji) => {
              const count =
                message.reactions?.filter(
                  (r: any) => r.emoji === emoji
                ).length || 0;
              const hasReacted = userReactions?.some(
                (r: any) => r.emoji === emoji
              );

              return (
                <button
                  key={emoji}
                  onClick={() =>
                    handleReaction(
                      message._id,
                      emoji,
                      hasReacted || false
                    )
                  }
                  className={`text-xs px-2 py-0.5 rounded ${
                    hasReacted
                      ? "bg-blue-100 dark:bg-blue-900"
                      : "bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600"
                  }`}
                >
                  {emoji} {count > 0 && count}
                </button>
              );
            })}
          </div>
        )}
      </div>
    </div>

      {/* Render replies (threaded) */}
      {replies.length > 0 && (
        <div className="mt-1">
          {replies.map((reply) => (
            <MessageItem
              key={reply._id}
              message={reply}
              user={user}
              members={members}
              handleReaction={handleReaction}
              allMessages={allMessages}
              onAttachAtom={onAttachAtom}
              onResendMessage={onResendMessage}
              onReferenceAtom={onReferenceAtom}
              isInputEmpty={isInputEmpty}
              isReply={true}
            />
          ))}
        </div>
      )}
    </div>
  );
}

// Inner component that has access to PlaybackContext
function SpacePageContent() {
  const { currentTrackId } = usePlayback();
  const { signOut } = useAuthActions();
  const params = useParams();
  const router = useRouter();
  const searchParams = useSearchParams();
  const spaceId = params.id as Id<"spaces">;

  const user = useQuery(api.users.current);
  const space = useQuery(api.spaces.get, { id: spaceId });
  const rooms = useQuery(api.rooms.list, { spaceId });
  const members = useQuery(api.spaces.getMembers, { spaceId });
  const generateInvite = useMutation(api.invites.generate);
  const kickMember = useMutation(api.spaces.kickMember);
  const sendMessage = useMutation(api.messages.send);
  const addReaction = useMutation(api.messages.addReaction);
  const removeReaction = useMutation(api.messages.removeReaction);
  const updatePresence = useMutation(api.presence.update);
  const generateImageUploadUrl = useMutation(api.atoms.generateImageUploadUrl);
  const createImageAtom = useMutation(api.atoms.createImageAtom);

  const [inviteCode, setInviteCode] = useState<string | null>(null);
  const [selectedRoomId, setSelectedRoomId] = useState<Id<"rooms"> | null>(null);
  const [messageContent, setMessageContent] = useState("");
  const [isCreateRoomOpen, setIsCreateRoomOpen] = useState(false);
  const [isRoomSettingsOpen, setIsRoomSettingsOpen] = useState(false);
  const [attachedAtomIds, setAttachedAtomIds] = useState<Id<"atoms">[]>([]);
  const [showAttachMenu, setShowAttachMenu] = useState(false);
  const [isUploadingImage, setIsUploadingImage] = useState(false);
  const [showSongMetadata, setShowSongMetadata] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const attachMenuRef = useRef<HTMLDivElement>(null);
  const imageInputRef = useRef<HTMLInputElement>(null);
  const messageInputRef = useRef<HTMLInputElement>(null);

  // Auto-show song metadata when a track starts playing (only once)
  useEffect(() => {
    if (currentTrackId && !showSongMetadata) {
      setShowSongMetadata(true);
    }
  }, [currentTrackId, showSongMetadata]);

  const { results: messages, status, loadMore } = usePaginatedQuery(
    api.messages.list,
    selectedRoomId ? { roomId: selectedRoomId } : "skip",
    { initialNumItems: 50 }
  );

  const isOwner = space && user?.user?._id === space.ownerId;
  const selectedRoom = rooms?.find((r) => r._id === selectedRoomId);

  // Query attached atoms to display in the dock
  const attachedAtoms = useQuery(
    api.atoms.getByIds,
    attachedAtomIds.length > 0 ? { ids: attachedAtomIds } : "skip"
  );

  // Read room from URL on mount, or auto-select first room
  useEffect(() => {
    // Only run this on initial load when selectedRoomId is not set
    if (selectedRoomId) return;

    const roomParam = searchParams.get("room");
    if (roomParam && rooms) {
      const roomExists = rooms.find((r) => r._id === roomParam);
      if (roomExists) {
        setSelectedRoomId(roomParam as Id<"rooms">);
        return;
      }
    }
    if (rooms && rooms.length > 0) {
      setSelectedRoomId(rooms[0]._id);
    }
  }, [rooms, searchParams, selectedRoomId]);

  // Update URL when room changes and focus input
  useEffect(() => {
    if (selectedRoomId) {
      const newUrl = `/space/${spaceId}?room=${selectedRoomId}`;
      router.replace(newUrl, { scroll: false });

      // Focus the message input when switching rooms (with a small delay to ensure it's rendered)
      setTimeout(() => {
        messageInputRef.current?.focus();
      }, 100);
    }
  }, [selectedRoomId, spaceId, router]);

  // Update presence
  useEffect(() => {
    if (user?.user?._id && spaceId && selectedRoomId) {
      updatePresence({ spaceId, roomId: selectedRoomId, status: "online" });
    }
  }, [user?.user?._id, spaceId, selectedRoomId, updatePresence]);

  // Scroll to bottom on new messages
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages]);

  // Close attach menu when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (attachMenuRef.current && !attachMenuRef.current.contains(event.target as Node)) {
        setShowAttachMenu(false);
      }
    };

    if (showAttachMenu) {
      document.addEventListener("mousedown", handleClickOutside);
    }
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [showAttachMenu]);

  const handleGenerateInvite = async () => {
    const result = await generateInvite({ spaceId });
    setInviteCode(result.code);
  };

  const handleKickMember = async (userId: Id<"users">) => {
    if (confirm("Are you sure you want to kick this member?")) {
      await kickMember({ spaceId, userId });
    }
  };

  const handleSendMessage = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!messageContent.trim() || !selectedRoomId) return;

    await sendMessage({
      roomId: selectedRoomId,
      content: messageContent,
      mentions: extractMentions(messageContent),
      atomIds: attachedAtomIds.length > 0 ? attachedAtomIds : undefined,
    });
    setMessageContent("");
    setAttachedAtomIds([]);
  };

  const handleResendMessage = async (content: string, atomIds?: Id<"atoms">[]) => {
    if (!selectedRoomId) return;

    await sendMessage({
      roomId: selectedRoomId,
      content,
      mentions: extractMentions(content),
      atomIds: atomIds && atomIds.length > 0 ? atomIds : undefined,
    });
  };

  const handleAttachAtom = (atomId: Id<"atoms">) => {
    if (!attachedAtomIds.includes(atomId)) {
      setAttachedAtomIds([...attachedAtomIds, atomId]);
    }
  };

  const handleReferenceAtom = (atomId: Id<"atoms">) => {
    // Prepopulate input if empty and add atom to references
    if (!messageContent.trim()) {
      setMessageContent("@suno remix this as ");
      // Focus the input at the end
      setTimeout(() => {
        const input = messageInputRef.current;
        if (input) {
          input.focus();
          input.setSelectionRange(input.value.length, input.value.length);
        }
      }, 10);
    }
    // Always add the atom to references
    if (!attachedAtomIds.includes(atomId)) {
      setAttachedAtomIds([...attachedAtomIds, atomId]);
    }
  };

  const handleRemoveAttachment = (atomId: Id<"atoms">) => {
    setAttachedAtomIds(attachedAtomIds.filter(id => id !== atomId));
  };

  const handleImageUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file || !spaceId) return;

    // Validate file is an image
    if (!file.type.startsWith("image/")) {
      alert("Please select an image file");
      return;
    }

    // Validate file size (max 10MB)
    if (file.size > 10 * 1024 * 1024) {
      alert("Image must be less than 10MB");
      return;
    }

    setIsUploadingImage(true);
    setShowAttachMenu(false);

    try {
      // Get upload URL
      const uploadUrl = await generateImageUploadUrl();

      // Upload file to Convex storage
      const result = await fetch(uploadUrl, {
        method: "POST",
        headers: { "Content-Type": file.type },
        body: file,
      });

      if (!result.ok) {
        throw new Error(`Upload failed: ${result.statusText}`);
      }

      const { storageId } = await result.json();

      // Get image dimensions
      let width: number | undefined;
      let height: number | undefined;
      try {
        const img = new Image();
        const imgUrl = URL.createObjectURL(file);
        img.src = imgUrl;
        await new Promise((resolve, reject) => {
          img.onload = resolve;
          img.onerror = () => reject(new Error("Failed to load image for dimension extraction"));
        });
        width = img.width;
        height = img.height;
        URL.revokeObjectURL(imgUrl);
      } catch (dimensionError) {
        console.warn("Could not extract image dimensions:", dimensionError);
        // Continue without dimensions - they're optional
      }

      // Create image atom
      const atomId = await createImageAtom({
        storageId,
        spaceId,
        width,
        height,
        filename: file.name,
      });

      // Attach to message
      handleAttachAtom(atomId);
    } catch (error) {
      console.error("Failed to upload image:", error);
      alert("Failed to upload image. Please try again.");
    } finally {
      setIsUploadingImage(false);
      if (imageInputRef.current) {
        imageInputRef.current.value = "";
      }
    }
  };

  const handleReaction = async (
    messageId: Id<"messages">,
    emoji: string,
    hasReacted: boolean
  ) => {
    if (hasReacted) {
      await removeReaction({ messageId, emoji });
    } else {
      await addReaction({ messageId, emoji });
    }
  };

  const extractMentions = (content: string): Array<Id<"users"> | "suno" | "orphy"> => {
    const mentions: Array<Id<"users"> | "suno" | "orphy"> = [];
    if (content.includes("@suno")) {
      mentions.push("suno");
    }
    // Backwards compatibility for @orphy
    if (content.includes("@orphy")) {
      mentions.push("orphy");
    }
    return mentions;
  };

  if (!user || !space) {
    return (
      <main className="flex min-h-screen items-center justify-center">
        <div className="text-center">
          <p>Loading...</p>
        </div>
      </main>
    );
  }

  if (space === null) {
    return (
      <main className="flex min-h-screen items-center justify-center">
        <div className="text-center">
          <p className="text-red-600 mb-4">Space not found or access denied</p>
          <Link href="/dashboard" className="text-blue-600 hover:underline">
            Back to Dashboard
          </Link>
        </div>
      </main>
    );
  }

  const themeColors = space.showcaseConfig?.theme || {
    primaryColor: "#3b82f6",
    backgroundColor: "#1f2937",
  };

  // Get room background style
  const getRoomBackgroundStyle = () => {
    if (!selectedRoom?.backgroundConfig) return {};

    const bg = selectedRoom.backgroundConfig;
    if (bg.type === "solid" && bg.solidColor) {
      return { background: bg.solidColor };
    } else if (bg.type === "gradient" && bg.gradientStart && bg.gradientEnd) {
      return { background: `linear-gradient(135deg, ${bg.gradientStart}, ${bg.gradientEnd})` };
    } else if (bg.type === "image" && bg.imageUrl) {
      return {
        backgroundImage: `url(${bg.imageUrl})`,
        backgroundSize: "cover",
        backgroundPosition: "center",
      };
    }
    return {};
  };

  return (
    <>
      <CreateRoomModal
        spaceId={spaceId}
        isOpen={isCreateRoomOpen}
        onClose={() => setIsCreateRoomOpen(false)}
        onRoomCreated={(roomId) => setSelectedRoomId(roomId)}
      />
      <RoomSettingsModal
        room={selectedRoom ?? null}
        isOpen={isRoomSettingsOpen}
        onClose={() => setIsRoomSettingsOpen(false)}
      />
      <main className="h-screen flex flex-col bg-gray-50 dark:bg-gray-900">
      {/* Top navigation bar */}
      <nav className="bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 flex-shrink-0">
        <div className="px-4 h-14 flex items-center justify-between">
          <div className="flex items-center gap-4">
            <Link href="/dashboard" className="text-sm text-blue-600 hover:underline">
              ← Dashboard
            </Link>
            <h1 className="text-lg font-bold">{space.name}</h1>
            {selectedRoom && (
              <>
                <span className="text-gray-400">/</span>
                <span className="text-gray-600 dark:text-gray-400">
                  #{selectedRoom.name}
                </span>
                <button
                  onClick={() => setIsRoomSettingsOpen(true)}
                  className="text-gray-500 hover:text-gray-700 dark:hover:text-gray-300"
                  title="Room Settings"
                >
                  <Settings className="w-4 h-4" />
                </button>
              </>
            )}
          </div>
          <div className="flex items-center gap-4">
            <Link
              href="/settings"
              className="text-sm text-blue-600 hover:underline"
            >
              Settings
            </Link>
            <span className="text-sm text-gray-600 dark:text-gray-400">
              {user.profile?.displayName || user.user?.name || user.user?.email}
            </span>
            <button
              onClick={() => signOut()}
              className="text-sm text-red-600 hover:text-red-700"
            >
              Sign Out
            </button>
          </div>
        </div>
      </nav>

      {/* Main content area with sidebar layout */}
      <div className="flex-1 flex overflow-hidden">
        {/* Left sidebar - Room list */}
        <div className="w-60 bg-gray-100 dark:bg-gray-800 border-r border-gray-200 dark:border-gray-700 flex-shrink-0 overflow-y-auto">
          <div className="p-4">
            <div className="flex items-center justify-between mb-2">
              <h3 className="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase">
                Rooms
              </h3>
              <button
                onClick={() => setIsCreateRoomOpen(true)}
                className="text-gray-500 hover:text-gray-700 dark:hover:text-gray-300"
                title="Create Room"
              >
                <Plus className="w-4 h-4" />
              </button>
            </div>
            <div className="space-y-1">
              {rooms && rooms.length > 0 ? (
                rooms.map((room) => (
                  <RoomListItem
                    key={room._id}
                    room={room}
                    isSelected={selectedRoomId === room._id}
                    onClick={() => setSelectedRoomId(room._id)}
                  />
                ))
              ) : (
                <p className="text-sm text-gray-500 px-3">No rooms</p>
              )}
            </div>
          </div>
        </div>

        {/* Middle - Chat area */}
        <div className="flex-1 flex flex-col" style={getRoomBackgroundStyle()}>
          {selectedRoom ? (
            <>
              {/* Messages area */}
              <div className="flex-1 overflow-y-auto p-4">
                <div className="max-w-4xl mx-auto space-y-4">
                  {status === "CanLoadMore" && (
                    <button
                      onClick={() => loadMore(20)}
                      className="w-full py-2 text-sm text-blue-600 hover:underline"
                    >
                      Load more messages
                    </button>
                  )}

                  {messages
                    ?.slice()
                    .reverse()
                    .filter((message) => !message.replyToId) // Only show top-level messages
                    .map((message) => (
                      <MessageItem
                        key={message._id}
                        message={message}
                        user={user}
                        members={members}
                        handleReaction={handleReaction}
                        allMessages={messages}
                        onAttachAtom={handleAttachAtom}
                        onResendMessage={handleResendMessage}
                        onReferenceAtom={handleReferenceAtom}
                        isInputEmpty={!messageContent.trim()}
                      />
                    ))}

                  <div ref={messagesEndRef} />
                </div>
              </div>

              {/* Message composer with glass effect */}
              <div className="p-4">
                <form onSubmit={handleSendMessage} className="max-w-4xl mx-auto">
                  {/* Attachment dock - shows attached atoms */}
                  {attachedAtoms && attachedAtoms.length > 0 && (
                    <div className="mb-3 p-3 backdrop-blur-md bg-white/70 dark:bg-gray-900/70 border border-white/30 dark:border-gray-700/40 rounded-lg shadow-xl">
                      <div className="text-xs font-medium text-gray-600 dark:text-gray-400 mb-2">
                        Attached ({attachedAtoms.length})
                      </div>
                      <div className="space-y-2">
                        {attachedAtoms.map((atom) => atom && (
                          <div key={atom._id} className="flex items-center gap-2 p-2 bg-gray-50 dark:bg-gray-800 rounded-lg">
                            {atom.type === "image" && atom.metadata.storageId ? (
                              <ImageThumbnail storageId={atom.metadata.storageId} />
                            ) : atom.metadata.albumArtUrl ? (
                              <img
                                src={atom.metadata.albumArtUrl}
                                alt=""
                                className="w-8 h-8 rounded object-cover flex-shrink-0"
                              />
                            ) : null}
                            <div className="flex-1 min-w-0">
                              <div className="text-sm font-medium text-gray-900 dark:text-gray-100 truncate">
                                {atom.type === "image"
                                  ? (atom.metadata.filename || atom.metadata.prompt || "Image")
                                  : (atom.metadata.tags || atom.metadata.title || "Untitled")}
                              </div>
                            </div>
                            <button
                              type="button"
                              onClick={() => handleRemoveAttachment(atom._id as Id<"atoms">)}
                              className="p-1 text-gray-400 hover:text-red-600 dark:hover:text-red-400 flex-shrink-0"
                              aria-label="Remove attachment"
                            >
                              <X size={16} />
                            </button>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}

                  {/* Message input bar */}
                  <div className="relative backdrop-blur-md bg-white/70 dark:bg-gray-900/70 border border-white/30 dark:border-gray-700/40 rounded-full shadow-xl p-1 flex items-center gap-2">
                    {/* Add attachment button */}
                    <div className="relative" ref={attachMenuRef}>
                      <button
                        type="button"
                        onClick={() => setShowAttachMenu(!showAttachMenu)}
                        className="ml-2 p-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 transition-colors"
                        aria-label="Add attachment"
                      >
                        <Plus size={20} />
                      </button>

                      {/* Attachment menu */}
                      {showAttachMenu && (
                        <div className="absolute bottom-full left-0 mb-2 w-48 backdrop-blur-md bg-white/90 dark:bg-gray-900/90 border border-white/30 dark:border-gray-700/40 rounded-lg shadow-xl overflow-hidden">
                          <button
                            type="button"
                            disabled
                            className="w-full px-4 py-3 text-left text-sm text-gray-400 dark:text-gray-500 hover:bg-gray-50 dark:hover:bg-gray-800 flex items-center gap-3 cursor-not-allowed opacity-50"
                          >
                            <Mic size={18} />
                            Record (Coming soon)
                          </button>
                          <button
                            type="button"
                            onClick={() => imageInputRef.current?.click()}
                            disabled={isUploadingImage}
                            className="w-full px-4 py-3 text-left text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-800 flex items-center gap-3 border-t border-gray-200 dark:border-gray-700 disabled:opacity-50 disabled:cursor-not-allowed"
                          >
                            <Upload size={18} />
                            {isUploadingImage ? "Uploading..." : "Upload image"}
                          </button>
                        </div>
                      )}
                      {/* Hidden file input */}
                      <input
                        ref={imageInputRef}
                        type="file"
                        accept="image/*"
                        onChange={handleImageUpload}
                        className="hidden"
                      />
                    </div>

                    <input
                      ref={messageInputRef}
                      type="text"
                      value={messageContent}
                      onChange={(e) => setMessageContent(e.target.value)}
                      placeholder={`Message #${selectedRoom.name}`}
                      className="flex-1 px-4 py-3 pr-24 bg-transparent focus:outline-none placeholder-gray-500 dark:placeholder-gray-400"
                    />
                    <button
                      type="submit"
                      disabled={!messageContent.trim()}
                      className="absolute right-2 px-5 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-400 text-white text-sm font-medium rounded-full transition-colors shadow-md"
                    >
                      Send
                    </button>
                  </div>
                </form>
              </div>

              {/* PlayBar underneath chat bar */}
              {selectedRoom.type === "radio" ? (
                <RadioPlayBar
                  roomId={selectedRoomId!}
                  currentUserId={user.user?._id}
                  onReferenceAtom={handleReferenceAtom}
                />
              ) : (
                <PlayBar roomId={selectedRoomId!} />
              )}
            </>
          ) : (
            <div className="flex-1 flex items-center justify-center">
              <div className="text-center text-gray-500">
                <p className="mb-2">Select a room to start chatting</p>
              </div>
            </div>
          )}
        </div>

        {/* Right sidebar - Atom Action Panel or Members */}
        {showSongMetadata && currentTrackId ? (
          <AtomActionPanel
            atomId={currentTrackId}
            onClose={() => setShowSongMetadata(false)}
            currentUserId={user.user?._id}
          />
        ) : (
          <div className="w-60 bg-white dark:bg-gray-800 border-l border-gray-200 dark:border-gray-700 flex-shrink-0 overflow-y-auto">
            <div className="p-4">
              <h3 className="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase mb-3">
                Members ({members?.length || 0})
              </h3>
            {members && members.length > 0 ? (
              <div className="space-y-2">
                {members.map((member) => {
                  const displayName =
                    member.profile?.displayName ||
                    member.user?.name ||
                    member.user?.email;
                  const avatar = member.profile?.avatar;

                  return (
                    <div
                      key={member._id}
                      className="flex items-center justify-between gap-2"
                    >
                      <div className="flex items-center gap-2 min-w-0">
                        {/* Avatar */}
                        <div className="relative flex-shrink-0">
                          {avatar ? (
                            <img
                              src={avatar}
                              alt={displayName}
                              className="w-8 h-8 rounded-full object-cover"
                            />
                          ) : (
                            <div className="w-8 h-8 rounded-full bg-gray-300 dark:bg-gray-600 flex items-center justify-center">
                              <span className="text-xs text-gray-600 dark:text-gray-300">
                                {displayName?.charAt(0).toUpperCase()}
                              </span>
                            </div>
                          )}
                          {/* Presence indicator */}
                          <div
                            className={`absolute bottom-0 right-0 w-2.5 h-2.5 rounded-full border-2 border-white dark:border-gray-800 ${
                              member.presence?.status === "online"
                                ? "bg-green-500"
                                : member.presence?.status === "idle"
                                ? "bg-yellow-500"
                                : "bg-gray-400"
                            }`}
                          />
                        </div>
                        <div className="text-sm truncate">
                          {displayName}
                          {member.role === "owner" && (
                            <span className="ml-1 text-xs text-gray-500">
                              (owner)
                            </span>
                          )}
                        </div>
                      </div>
                      {isOwner && member.role !== "owner" && (
                        <button
                          onClick={() => handleKickMember(member.userId)}
                          className="text-xs text-red-600 hover:text-red-700 flex-shrink-0"
                        >
                          Kick
                        </button>
                      )}
                    </div>
                  );
                })}
              </div>
            ) : (
              <p className="text-sm text-gray-500">No members</p>
            )}

            {/* Invite section */}
            {isOwner && (
              <div className="mt-6 pt-6 border-t border-gray-200 dark:border-gray-700">
                <h3 className="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase mb-3">
                  Invite
                </h3>
                {inviteCode ? (
                  <div>
                    <p className="text-xs text-gray-600 dark:text-gray-400 mb-2">
                      Share this code:
                    </p>
                    <code className="block p-2 bg-gray-100 dark:bg-gray-700 rounded text-xs font-mono break-all">
                      {inviteCode}
                    </code>
                    <button
                      onClick={() => setInviteCode(null)}
                      className="mt-2 text-xs text-blue-600 hover:underline"
                    >
                      Generate new
                    </button>
                  </div>
                ) : (
                  <button
                    onClick={handleGenerateInvite}
                    className="w-full bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium py-2 px-3 rounded transition-colors"
                  >
                    Generate Invite
                  </button>
                )}
              </div>
            )}
            </div>
          </div>
        )}
      </div>
    </main>
    </>
  );
}

function SpacePageWrapper() {
  const params = useParams();
  const searchParams = useSearchParams();
  const spaceId = params.id as Id<"spaces">;
  const selectedRoomId = searchParams.get("room") as Id<"rooms"> | null;

  return (
    <PlaybackProvider roomId={selectedRoomId}>
      <SpacePageContent />
    </PlaybackProvider>
  );
}

export default function SpacePage() {
  return (
    <Suspense fallback={
      <div className="flex min-h-screen items-center justify-center">
        <div className="text-center">
          <p>Loading...</p>
        </div>
      </div>
    }>
      <SpacePageWrapper />
    </Suspense>
  );
}
